import work_space.*;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;

public class Barista {
    private static final int PORT = 8080;

    private static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE = new ScheduledThreadPoolExecutor(
            2, Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

    static {
        SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(
                Barista::logServerState, 0, 5, TimeUnit.SECONDS);
    }

    public static void main(String[] args) {
        System.out.println("🟢 Virtual Caffee Barista Server Starting...");
        System.out.println("📍 Server listening on port: " + PORT);
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            while (true) {
                Socket clientSocket = serverSocket.accept();
                // 为每个客户端创建新线程
                Worker worker = new Worker(clientSocket);
                worker.start();
            }
        } catch (IOException e) {
            System.err.println("❌ Server error: " + e.getMessage());
        }
    }

    // 优雅处理Ctrl-C退出
    static {
        Runtime
                .getRuntime()
                .addShutdownHook(new Thread(() -> {
                    SCHEDULED_EXECUTOR_SERVICE.shutdown();
                    System.out.println("\n⚠️  Interrupted! Closing connection...");
                }));
    }


    // 记录服务器状态
    private static void logServerState() {
        System.out.println("\n=== Caffee Status Update ===");
        System.out.println("👥 Clients in caffee: " + WorkSpaceFactory.clientMap.size());
        System.out.println("⏳ Clients waiting for orders: " + WorkSpaceFactory.waitingArea.size());
        System.out.println(
                "🫖 Orders in waiting area: " + WorkSpaceFactory.waitingArea.size());
        System.out.println("🔥 Orders in brewing area: " + WorkSpaceFactory.brewingArea.size());
        System.out.println(
                "📦 Orders in tray area: " + WorkSpaceFactory.trayArea.size());
        System.out.println("==========================\n");
    }
}

